/**
 * Created by thomas on 2017/5/7.
 */
import React,{Component} from 'react';
import Loading_page from "./loading_page";
import limit from './limit_scroll';
import  ajax from "./ajax";
import { withRouter } from 'react-router-dom'
class Push_img extends React.Component{
    constructor(props) {
        super(props);
        this.state= {
            c_h: sessionStorage.getItem("c_h") - 40,
            rest_name: [false, false, false, false, false],
            select_res:"xx",
            hide_rest:true,
            hide_state:true,
            meat:[],
            greenstuff:[],
            staplefood:[],
            kcal:0,
            hid_load:true,
            data_none:false,
            ajax_mess:JSON.parse(sessionStorage.getItem("push_img_mess")),
            has_mess_pre_page:false//判断上一页是否有数据
        }
        this.hide1=this.hide1.bind(this);
        /*
        * {
         name:"",
         num:"",
         id:"",
         kcal:""
         }
         */
    }
    change_s_n(e){
            let temp = this.state.rest_name;
            temp.forEach((index,i)=>{
                temp[i] = false
            })
            temp[e] = true;
            this.setState({
                rest_name:temp,
            })
    }
    componentWillMount(){
        if(this.state.has_mess_pre_page == true){//true 上一页有数据yes~~
            this.change_state(
                name,//字段名
                this.state.ajax_mess[name][x].id,//食品id
                this.state.ajax_mess[name][x].dishname, //食品名字
                1,
                x,
                this.state.ajax_mess[name][x].energy
            )
        }
        try{
            for(let x = 0; x<this.state.ajax_mess.meat.length;x++){
                this.state.ajax_mess.meat[x].click_count=0
            }
            for(let x = 0; x<this.state.ajax_mess.staplefood.length;x++){
                this.state.ajax_mess.staplefood[x].click_count=0
            }
            for(let x = 0; x<this.state.ajax_mess.greenstuff.length;x++){
                this.state.ajax_mess.greenstuff[x].click_count=0
            }
        }catch(e){
            this.setState({
                data_none:true
            })
        }

    }
    componentDidMount(){
        console.log(this.refs.contain_Push_img);

        try{
            limit(this.refs.contain_Push_img,this.refs.warp_push_img_box);
        }catch (e){
            console.log(e);
            limit(this.refs.contain_Push_img,this.refs.warp_push_img_box);
            // console.log(e);
        }
        // console.log(this.refs.warp_push_img_box);

    }
    change_s_se(){
        let temp = this.state.rest_name;
        temp.forEach((index,i)=>{
            temp[i] = false
        })
        temp[e] = true;
        this.setState({
            rest_name:temp,
        })
    }
    setToolbar_se(){
        let tools = [];
        let ajax_mess = this.state.ajax_mess;
        // ajax_mess.messname.length
        for( let i = 0; i <ajax_mess.messname.length; i++ ){
            if(i == ajax_mess.messname.length-1){
                tools.push(
                    <div className="ok_btn_push_img" onClick={()=>this.hide1("push_img_header_right")}>
                        确认
                    </div>
                )
            }
            tools.push(
                <div className={
                    this.state.rest_name[i]
                        ?"rest_name act_rest_name"
                        :"rest_name"
                }  onClick={() =>this.change_s_n(i)}>
                    {this.state.ajax_mess.messname[0].name}
                </div>
            );
        }
        if(tools.length==0){
            tools.push(<div>&nbsp;</div>)
        }
        return tools;
    }
    setToolbar(){
        let ajax_mess = this.state.ajax_mess;
        let tools = [];
        for( let i = 0; i <ajax_mess.schoolname.length; i++ ){
            if(i == ajax_mess.schoolname.length-1){
                tools.push(
                    <div className="ok_btn_push_img" onClick={()=>this.hide1("push_img_header_left")}>
                        确认
                    </div>
                )
            }
            tools.push(
                // 现在没有 可以选择的 所以 都是active
                <div className={
                    this.state.rest_name[i]
                        ?"rest_name act_rest_name"
                        :"rest_name act_rest_name"
                }  onClick={() =>this.change_s_n(i)}>
                    {this.state.ajax_mess.schoolname[0].name}
                </div>

            );
        }
        if(tools.length==0){
            tools.push(<div>&nbsp;</div>)
        }
        return tools;
    }
    get_main(name){
        let main=[];
        if(this.state.data_none == true){
              main.push(
                  <div style={{fontSize:'20px',marginTop:"10px"}}>
                      暂无食品
                  </div>
              )
            return main
        }
        for (let x=0;x<this.state.ajax_mess[name].length;x++){
            main.push(
                    <div className="warp_push_img_box" ref="warp_push_img_box">
                        {/*onClick={()=>this.change_img(this.state.ajax_mess[name][x].id)}*/}
                    <div className='push_img_box'>
                        <div className="push_img_mask"></div>
                        <div className="input_num">

                            {this.state.data_none?0:this.state.ajax_mess[name][x].click_count}
                        </div>
                        <img src= {'http://woxiaoshitang.com/activity/Public/upload/Wx/'+this.state.ajax_mess[name][x].img} alt="" className="push_img_box_img"/>
                        <div className="push_img_bot">

                            <div className="push_img_bot_right" onClick={
                                () => {
                                    this.change_state(
                                        name,//字段名
                                        this.state.ajax_mess[name][x].id,//食品id
                                        this.state.ajax_mess[name][x].dishname, //食品名字
                                        1,
                                        x,
                                        this.state.ajax_mess[name][x].energy
                                    )}
                            }>
                                &nbsp;
                            </div>
                            <div className="push_img_bot_right push_img_bot_right_active change_p_pi"

                                 onClick={
                                     () => this.change_state(
                                                    name,//字段名
                                                    this.state.ajax_mess[name][x].id,//食品id
                                                    this.state.ajax_mess[name][x].dishname, //食品名字
                                                     -1,//count -1
                                                      x,//index
                                                     this.state.ajax_mess[name][x].energy
                                                    )
                                 }>
                                &nbsp;
                            </div>
                        </div>
                    </div>
                    <div className="push_img_bot_name">
                        <span>{this.state.ajax_mess[name][x].dishname}</span>
                        <span>{this.state.ajax_mess[name][x].energy}kcal</span>
                    </div>
                    </div>
                )
        }
        return main
    }
    hide1(e){
        if(e == "push_img_header_left"){
           this.setState({
               hide_rest:!this.state.hide_rest,
               hide_state:this.state.hide_rest?true:true
           })
        }
        if(e == "push_img_header_right"){
            this.setState({
                hide_state:!this.state.hide_state,
                hide_rest:true
            })
        }
    }
    show_bottom(){
            let sum=[];
            let fuck = "x";
            for(let x=0;x< this.state.staplefood.length;x++){//fuck 是 x乘号~~
                this.state.staplefood[0].name == null?fuck="":fuck="x";
                sum.push(this.state.staplefood[x].name +fuck+
                    this.state.staplefood[x].num)
            }
            for(let x=0 ;x<this.state.greenstuff.length;x++) {
                this.state.greenstuff[0].name == null?fuck="":fuck="x";
                sum.push( this.state.greenstuff[x].name + fuck+
                    this.state.greenstuff[x].num)
            }
            for(let x=0;x<this.state.meat.length;x++){
                this.state.meat[0].name == null?fuck="":fuck="x";

                sum.push(this.state.meat[x].name + fuck+
                    this.state.meat[x].num)
            }
            return sum;
    }

    //插入数据
    change_state(name,id,food_name,count,x,kcal){
        let ajax_mess = this.state.ajax_mess;//当前的ajax_mess
        let push_flag = true;//判断是否push进去

        if(count == -1 && ajax_mess[name][x].click_count ==0){
            return
        }

        ajax_mess[name][x].click_count+=count;//改变 count
        this.setState({
             ajax_mess:ajax_mess
        });

        //判断是否有相同的 有酒不插入
        let num= this.state[name];
        for(let x = 0;x < this.state[name].length; x++){
            if(this.state[name][x].name == food_name){//如果食品名字相同就 加数量
                num[x].num= "" ? num[x].num = 1 : num[x].num += count;
                this.setState({
                    kcal : this.state.kcal = this.state.kcal + parseInt(kcal) * count,
                });
                push_flag= false;
            }
        }

        //当没有数量后就 把他出数组中去掉
        if(count < 0  &&  ajax_mess[name][x].click_count == 0){
            let temp = this.state[name];
             for(let x=0; x<temp.length;x++){
                 if(food_name == temp[x].name){
                     temp.splice(x)
                 }
             }
            push_flag = false
        }

        if(push_flag){//没有相同的 插入数据 食品名字只有一个！！！
            let val=this.state[name];
            let temp={
                name:food_name,
                num:  ajax_mess[name][x].click_count,
                id:id,
                kcal:kcal
            };
            val.push(temp);
            this.setState({
                [name] :val,
                kcal:this.state.kcal+=parseInt(kcal)
            },()=>{
                // console.log(this.state.greenstuff)
                // console.log(this.state[name])
            })
        }
    }

    up_load(){
        this.setState({
            hid_load:false
        });
        let sel=[];
        let kcal_c = 0;//某一个的能量 菜
        let kcal_meat = 0;//肉
        let kcal_sfood = 0;// 主
        // console.log(this.state.greenstuff)
        for(let x=0 ;x<this.state.greenstuff.length;x++){
            for(let y=0 ;y<this.state.greenstuff[x].num;y++){
                sel.push({
                    content:this.state.greenstuff[x].name,
                    energy:this.state.greenstuff[x].kcal
                })
            }
        }

        for(let x=0 ;x<this.state.meat.length;x++){
            for(let y=0 ;y<this.state.meat[x].num;y++){
                sel.push({
                    content:this.state.meat[x].name,
                    energy:this.state.meat[x].kcal
                })
            }
        }

        for(let x=0 ;x<this.state.staplefood.length;x++){
            for(let y=0 ;y<this.state.staplefood[x].num;y++){
                sel.push({
                    content:this.state.staplefood[x].name,
                    energy:this.state.staplefood[x].kcal
                    // number:this.state.staplefood[x].num
                })
            }
        }

        $.ajax({
            url:"http://woxiaoshitang.com/activity/health.php/Index/setenergy",
            data:{
                userid:sessionStorage.getItem("userid"),
                [sessionStorage.getItem("sel_record")]:sel,
                [sessionStorage.getItem("eng")]:this.state.kcal,
                message:sessionStorage.getItem("mess_push"),
                time:sessionStorage.getItem("now_time"),
            },
            type:"post",
            success:(e)=>{
                setTimeout(()=>{
                    this.change_reord_mess();
                },0)
            }
        })
    }
    change_reord_mess(){
        let sex = sessionStorage.getItem("sex") =="wm" ? sex=0:sex=1;
        let openid = sessionStorage.getItem("op_id");
        let t=sessionStorage.getItem("now_time_s");
        openid=openid.replace(/\s/g,"");
        ajax({
            meth:"post",
            url:"http://woxiaoshitang.com/activity/health.php/Index/ajaxtime",
            data:"sex="+sex+"&openid="+sessionStorage.getItem("op_id")+"&time="+t,
            cb:(e) =>{
                //返回数据没有时间， 这里拼接
                e = JSON.parse(e);
                e.time = parseInt(t);
                e.static_time = sessionStorage.getItem("static_time");
                e = JSON.stringify(e);
                sessionStorage.setItem("record_mess",e);
                sessionStorage.setItem("push_img_set_time",true);
                // this.props.history.push("/record");
                this.props.history.goBack()
            }
        })
    }
    render(){
        return (
            <div className="contain_Push_img" ref="contain_Push_img">
                <Loading_page hid_load = {this.state.hid_load}/>
               <header className="push_img_header">
                   <div className={this.state.hide_rest?"push_img_header_left":"push_img_header_left"} onClick={()=>this.hide1("push_img_header_left")}>
                       {this.state.ajax_mess.schoolname[0].name}
                   </div>
                   <div className={this.state.hide_rest?"rest_name_wrap hidden_act":"rest_name_wrap "} style={{height:this.state.c_h+"px"}} ref="rest_name_wrap">
                       {
                          this.setToolbar()
                       }
                   </div>
                   <div  className="push_img_header_right" onClick={()=>this.hide1("push_img_header_right")}>
                       {this.state.ajax_mess.messname[0].name}
                   </div>
                   <div className={this.state.hide_state?"rest_name_wrap hidden_act":"rest_name_wrap "} style={{height:this.state.c_h+"px"}} ref="rest_name_wrap">
                       {
                           this.setToolbar_se()
                       }
                   </div>
               </header>
               <div className="wrap_push_img_main" ref="wrap_push_img_main">
               <div className="push_img_main push_img_top">
                   <div className="push_img_main_header">
                       主食
                   </div>
                   <div className="wrap_push_img_main">
                       {
                        this.get_main("staplefood")
                       }
                   </div>
                   <div className="push_img_main_header">
                       蔬菜
                   </div>
                   <div className="wrap_push_img_main">
                       {
                           this.get_main("greenstuff")
                       }
                   </div>
                   <div className="push_img_main_header">
                       肉类
                   </div>
                   <div className="wrap_push_img_main">
                       {
                           this.get_main("meat")
                       }
                   </div>
               </div>
               </div>
                <div className="push_img_bottom">
                    <div className="push_img_text">
                        你本餐吃了
                        {this.show_bottom()}
                        。已摄入热量{this.state.kcal} kcal。
                    </div>
                </div>
                <div className="push_img_s_btn" onClick={()=>this.up_load()}>提交</div>
            </div>
        );
    }
}
export default withRouter(Push_img);
